package org.example.controller;

import org.example.api.IUserService;
import org.example.api.entity.User;
import org.example.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: Re
 * @Date: 2021/4/18 13:57
 */
@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;utf-8");
        req.setCharacterEncoding("UTF-8");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        if (userName==null || "".equals(userName)) {
            req.setAttribute("msg","用户名不能为空");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
            return;
        }
        if (userPassword==null || "".equals(userPassword)) {
            req.setAttribute("msg","密码不能为空");
            req.getRequestDispatcher("signIn.jsp").forward(req,resp);
            return;
        }
        IUserService iUserService = new UserServiceImpl();
        User user = new User(userName,userPassword);
        User user1 = iUserService.checkUser(user);
        if (user1 == null){
            req.setAttribute("msg","用户不存在");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
            return;
        }
        System.out.println(user.getUserId());
        if (userName.equals(user1.getUserName())&&userPassword.equals(user1.getUserPassword())){
            HttpSession session = req.getSession();
            session.setAttribute("user",user1);
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        }else {
            req.setAttribute("msg","登录失败");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
